<template>
  <el-dialog
    v-model="dialog.visible"
    :title="title"
    width="500px"
    height="500px"
    @close="handleCloseDialog"
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" class="form">
      <el-form-item label="头像" prop="avatar">
        <SingleImageUpload v-model="formData.avatar" :style="uploadStyle" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="formData.nickname" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input
          v-model="formData.mobile"
          placeholder="请输入手机号码"
          :maxlength="11"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="code" class="form-item-class">
        <el-input
          v-model="formData.code"
          :placeholder="$t('login.code')"
          @keyup.enter="handleSubmit"
        >
          <template #append>
            <CodeButton
              :mobile="formData.mobile"
              smsType="REGISTER"
              :validateFunction="validateFunction"
              @getCode="(code) => (formData.code = code)"
              ref="codeButs"
            />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="性别" prop="userType">
        <enum-select
          v-model="formData.gender"
          placeholder="请选择"
          :enums="GenderEnum"
          style="width: 100%"
        ></enum-select>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" type="password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="角色" prop="roleIds">
        <el-select
          v-model="formData.roleIds"
          placeholder="请选择角色"
          clearable
          multiple
          :multiple-limit="1"
        >
          <el-option
            v-for="dict in roleList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCloseDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { getAccessToken } from "@/utils/auth";
import { GenderEnum, UserTypeEnum } from "@/enums/system/UserEnum";
import EnumSelect from "@/components/EnumSelect/index.vue";
import { ElMessage, UploadProps } from "element-plus";
import UserAPI, { UserForm } from "@/api/system/user";
import RoleAPI from "@/api/system/role";
import CodeButton from "@/components/SmsCode/CodeButton.vue";
// 定义 emit，用于通知外部关闭事件
const emit = defineEmits(["update:modelValue", "loadData"]);
// 弹窗
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  defaultRowId: {
    type: String,
    default: "",
  },
  data: {
    type: Object,
  },
  id: {},
});

const uploadStyle = {
  width: "100px",
  height: "100px",
};
const dialog = reactive({
  title: "",
  visible: false,
});
const formRef = ref();
const roleList = ref([]);
const codeButs = ref();

const defaultFormData: UserForm = {
  nickname: "",
  userType: UserTypeEnum.PRACTITIONER.value,
  mobile: "",
  password: "",
  gender: 1,
  avatar: "",
  email: "",
  status: 0,
  companyId: 0,
  roleIds: [],
  openId: "",
};
const formData = ref<UserForm>({
  ...defaultFormData,
});
const formRules = reactive({
  mobile: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入有效的手机号码", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { len: 6, message: "验证码长度为6位", trigger: "blur" },
  ],
  nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  roleIds: [{ required: true, message: "请选择角色", trigger: "change" }],
});
const title = computed(() => {
  return formData.value.id ? "编辑" : "新增";
});
const isEdit = computed(() => {
  return !!formData.value.id;
});

// 监听外部传入的 modelValue，更新内部 visible 状态
watch(
  () => props.modelValue,
  (newValue) => {
    dialog.visible = newValue;
    if (newValue) {
      formData.value = {
        ...defaultFormData,
      };
      getRoleList();
      if (!props.id) return;
      getFormData();
    }
  }
);

const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  formData.value.avatar = URL.createObjectURL(uploadFile.raw!);
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("格式不正确，请选择jpeg或者png格式图片");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不超过2MB!");
    return false;
  }
  return true;
};

async function handleSubmit() {
  const validate = await formRef.value.validate();
  if (!validate) return;
  try {
    if (formData.value.id) {
      await UserAPI.update(formData.value.id, formData.value);
    } else {
      await UserAPI.add(formData.value);
    }
    ElMessage.success("成功");
    emit("loadData");
    handleCloseDialog();
  } catch (error) {
    console.log("error", error);
  }
}

async function getRoleList() {
  try {
    const data: any = await RoleAPI.getOptions();
    roleList.value = data.data || [];
  } catch (e) {
    console.log(e);
  }
}
async function getFormData() {
  try {
    const data: any = await UserAPI.getFormData(props.id);
    formData.value = {
      ...defaultFormData,
      ...data.data,
    };
  } catch (e) {
    console.log(e);
  }
}

// 关闭弹窗
function handleCloseDialog() {
  codeButs.value.setCode();
  dialog.visible = false;
  emit("update:modelValue", false); // 关闭弹窗
}
const validateFunction = async (mobile: string) => {
  console.log(mobile);
  const result = await formRef.value?.validateField("mobile", (valid) => {
    if (valid) {
      console.log("valid");
      return true;
    } else {
      ElMessage.error("请输入有效的手机号码");
      return false;
    }
  });
  console.log(result);
  return result;
};
</script>
<style style="scss" scoped>
::v-deep(.el-tabs__content) {
  min-height: 100px;
  display: flex;
  align-items: center;
}
</style>
